package kr.ac.ml.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ac.kr.ml.dao.ContentListDao;
/*import net.sf.json.JSONObject;*/
import ac.kr.ml.dao.ListDao;
import ac.kr.ml.dao.UserDao;
import ac.kr.ml.vo.ContentVo;
import ac.kr.ml.vo.FriendVo;
import ac.kr.ml.vo.WriteVo;
import kr.ac.ml.mvc.Action;



public class WriteAction extends Action {

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		System.out.println("WriteAction");	

		String content = request.getParameter("content");
		String MaxContentId = request.getParameter("MaxContentId");
		int con_id = Integer.parseInt(MaxContentId);
		String keyStr = request.getParameter("key");
		int key = Integer.parseInt(keyStr);
		String time;
		WriteVo vo = new WriteVo();
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat dataFormat = new SimpleDateFormat("yy.MM.dd HH:mm:ss");
		time = dataFormat.format(calendar.getTime());

		vo.setContent(content);		
		vo.setTime(time);
		vo.setBad(0);
		vo.setGood(0);
		vo.setReply_cont(0);
		vo.setCnt_writer(key);
		
		UserDao dao = new UserDao();
		
		List<FriendVo> friendList = dao.getFriend(key);

		ContentListDao dao2 = new ContentListDao();
		dao2.insert(vo);

		
		List<WriteVo> list = new ArrayList<WriteVo>();
				
		list = dao2.getInsertList(con_id, friendList, key);		

		String jsonStr = "";

		int length = list.size();

		jsonStr += "{";
		jsonStr += "\"InsertList\":[";

		for(int i = 0; i < length; i++){
			jsonStr += "{";
			jsonStr += 		"\"con_id\":\"" + list.get(i).getCon_id() + "\",";
			jsonStr += 		"\"content\":\"" + list.get(i).getContent() + "\",";
			jsonStr +=		"\"time\":\"" + list.get(i).getTime() + "\",";
			jsonStr += 		"\"good\":\"" + list.get(i).getGood() + "\",";
			jsonStr += 		"\"bad\":\"" + list.get(i).getBad() + "\",";
			jsonStr += 		"\"reply_cont\":\"" + list.get(i).getReply_cont() + "\",";
			jsonStr +=		"\"cnt_writer\":\"" + list.get(i).getCnt_writer() + "\"";
			jsonStr += "}";

			if(i < length - 1) jsonStr += ",";
		}

		jsonStr += "]";
		jsonStr += "}";


		request.setAttribute("json", jsonStr);


	}

}
